// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成
package com.fowo.api.datainterface.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.R;
import com.fowo.api.datainterface.constants.DatainterfaceTypeKind;
import com.fowo.api.datainterface.model.DataContextModel;
import com.fowo.api.datainterface.entity.DatainterfaceTask;
import com.fowo.api.datainterface.model.DatainterfaceTaskSearchParamPo;
import com.fowo.api.datainterface.model.DatainterfaceTaskVo;
import com.fowo.api.datainterface.service.DatainterfaceTaskService;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Tag(name = "数据接口事务")
@RequestMapping("/api/datainterface-task")
@RestController
public class DatainterfaceTaskController {

    @Resource
    private DatainterfaceTaskService service;
    @Resource
    private DatainterfaceTaskService datainterfaceTaskService;

    @Resource
    private SysSerialService sysSerialService;

    @Operation(summary = "查询结果")
    @GetMapping
    public R<List<DatainterfaceTask>> search(
            DatainterfaceTaskSearchParamPo search
    ) {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        if (jwtUserInfo != null) {
//            search.setCurrentUserId(jwtUserInfo.getUserId());
        }
        return R.data(service.search(search));
    }

    @Operation(summary = "查询最后更新时间")
    @GetMapping("lastUpdateTime")
    public R<Date> searchLastUpdateTime(DatainterfaceTaskSearchParamPo search) {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        if (jwtUserInfo != null) {
//            search.setCurrentUserId(jwtUserInfo.getUserId());
        }
        return R.data(service.searchLastUpdateTime(search));
    }

    @Operation(summary = "获取分页查询结果")
    @GetMapping("page")
    public R<Page<DatainterfaceTask>> getPage(
            DatainterfaceTaskSearchParamPo search
    ) {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        if (jwtUserInfo != null) {
            search.setCurrentUserId(jwtUserInfo.getUserId());
        }
        return R.data(service.pageSearch(search));
    }

    @Operation(summary = "获取详情")
    @GetMapping("{id}")
    public R<DatainterfaceTaskVo> getVoById(@PathVariable Long id) {
        return R.data(() -> service.getVoById(id));
    }

    @Operation(summary = "获取源接口编码相关的编号列表")
    @GetMapping("en-code-from/{texts}/ids")
    public R<List<Long>> getIdsByEnCodeFrom(@PathVariable String texts) {
        List<String> nameList = Arrays
                .stream(texts.split(","))
                .collect(Collectors.toList());
        return R.data(() -> service.getIdsByEnCodeFrom(nameList));
    }

    @Operation(summary = "获取编号相关的源接口编码列表")
    @GetMapping("en-code-from/{ids}")
    public R<List<String>> getVoById(@PathVariable String ids) {
        List<Long> idList = Arrays
                .asList(ids.split(","))
                .stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        return R.data(() -> service.getEnCodeFromByIds(idList));
    }

    @PreAuthorize("@am.canAccess('datainterfaceTaskCreate')")
    @Operation(summary = "新增")
    @PostMapping
    public R<Long> create(@Validated @RequestBody DatainterfaceTaskVo model) {
        return R.data(() -> service.create(model));
    }

    @PreAuthorize("@am.canAccess('datainterfaceTaskEdit')")
    @Operation(summary = "更新")
    @PutMapping
    public R update(@RequestBody DatainterfaceTaskVo model) {
        return R.run(() -> service.update(model));
    }

    @PreAuthorize("@am.canAccess('datainterfaceTaskEdit')")
    @Operation(summary = "编辑更新")
    @PutMapping("edit")
    public R updateForEdit(@RequestBody DatainterfaceTaskVo model) {
        return R.run(() -> service.updateForEdit(model));
    }

    @PreAuthorize("@am.canAccess('datainterfaceTaskDelete')")
    @Operation(summary = "删除")
    @DeleteMapping("{id}")
    public R delete(@PathVariable Long id) {
        return R.run(() -> service.delete(id));
    }

    @PreAuthorize("@am.canAccess('datainterfaceTaskDelete')")
    @Operation(summary = "批量删除")
    @DeleteMapping("batch")
    public R batchDelete(@RequestBody IdListPo po) {
        return R.run(() -> service.batchDelete(po.getIds()));
    }


    @Operation(summary = "事务数据预览")
    @GetMapping("preview/{id}")
    public R<Object> getPreviewById(@PathVariable Long id) throws Exception {
        try {
            DatainterfaceTask byId = service.getById(id);
            if (ObjectUtil.isNotEmpty(byId)) {
                DataContextModel contextModel = DataContextModel.builder().build();
                contextModel.setTaskCode(byId.getTaskCode());
                contextModel = datainterfaceTaskService.getToInfoByTaskCode(contextModel, DatainterfaceTypeKind.From.getValue(), null, null);
                contextModel = datainterfaceTaskService.getToInfoByTaskCode(contextModel, DatainterfaceTypeKind.To.getValue(), (to) -> {
                    to.setEnvironment("preview");
                    return null;
                }, null);
                List<DataContextModel.DatainterfaceToModel> to = contextModel.getTo();
                Map<String, Object> map = new HashMap<>();
                for (DataContextModel.DatainterfaceToModel item : to) {
                    if (MapUtil.isNotEmpty(item.getCallJsData())) {
                        map.putAll(item.getCallJsData());
                    }
                }
                return R.data(map);
            }
            return R.fail("单据不存在！");
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }

    }


    @Operation(summary = "获取单号")
    @GetMapping("getNumber")
    public R<String> getNumber() throws Exception {
        try {
            String number = sysSerialService.getNewSerial(new NewSerialRequest(null, "DatainterfaceTask.taskCode"));
            return R.data(number);
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }
    }

    @Operation(summary = "拷贝")
    @GetMapping("copy/{id}")
    public R<String> copy(@PathVariable Long id) throws Exception {
        try {
            Boolean number = datainterfaceTaskService.copy(id);
            return R.ok(number);
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }
    }


}
